package com.bp.hearthealth.pulse.lnapps.bp_view
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.RectF
import android.util.AttributeSet
import android.util.TypedValue
import android.view.View
import com.bp.hearthealth.pulse.lnapps.R
import kotlin.math.cos
import kotlin.math.sin

class BPColorRingView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {

    private val colors = intArrayOf(
        0xFF027FFB.toInt(),
        0xFF2BBC8B.toInt(),
        0xFFF9DB18.toInt(),
        0xFFFFB900.toInt(),
        0xFFFF9501.toInt(),
        0xFFF64A10.toInt()
    )
    private var data = intArrayOf()
    private lateinit var validDataIndices: MutableList<Int> // 有效数据的索引列表
    private var totalData = 0

    private var strokeWidth: Float = 0f // 圆环宽度
    private var radius: Float = 0f // 圆环半径
    private var textOffset: Float = 0f // 文字偏移量

    init {
        initAttributes(context, attrs)
    }

    private fun initAttributes(context: Context, attrs: AttributeSet?) {
        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.ColorRingView)
        strokeWidth = typedArray.getDimension(
            R.styleable.ColorRingView_ring_stroke_width,
            TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 16f, resources.displayMetrics)
        )
        radius = typedArray.getDimension(
            R.styleable.ColorRingView_ring_radius,
            TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 55f, resources.displayMetrics)
        )
        textOffset = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10f, resources.displayMetrics) // 设置文字偏移量
        typedArray.recycle()
    }

    fun setData(data: IntArray) {
        this.data = data
        calculateTotalData()
        calculateValidDataIndices()
        invalidate() // 重新绘制
    }

    private fun calculateTotalData() {
        totalData = data.sum()
    }

    private fun calculateValidDataIndices() {
        validDataIndices = mutableListOf()
        for (i in data.indices) {
            if (data[i] != 0) {
                validDataIndices.add(i)
            }
        }
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)

        val width = width
        val height = height
        val centerX = width / 2f
        val centerY = height / 2f

        val rectF = RectF(centerX - radius, centerY - radius, centerX + radius, centerY + radius)
        var startAngle = -90f // 从12点钟方向开始
        val paint = Paint(Paint.ANTI_ALIAS_FLAG)
        paint.strokeWidth = strokeWidth
        paint.style = Paint.Style.STROKE

        // 绘制圆环
        for (index in validDataIndices) {
            val value = data[index]
            if (value == 0) continue // 跳过值为0的情况
            paint.color = colors[index]
            val sweepAngle = value.toFloat() / totalData * 360
            canvas.drawArc(rectF, startAngle, sweepAngle, false, paint)
            startAngle += sweepAngle

            // 绘制外部TextView
            val textPaint = Paint(Paint.ANTI_ALIAS_FLAG)
            textPaint.color = colors[index]
            textPaint.textSize =
                TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 12f, resources.displayMetrics)
            val textWidth = textPaint.measureText(value.toString())
            val radiusX =
                centerX + (radius + strokeWidth / 2 + textOffset) * cos(Math.toRadians((startAngle - sweepAngle / 2).toDouble()))
                    .toFloat()
            val radiusY =
                centerY + (radius + strokeWidth / 2 + textOffset) * sin(Math.toRadians((startAngle - sweepAngle / 2).toDouble()))
                    .toFloat()
            val textX = radiusX - textWidth / 2
            val textY = radiusY + textPaint.textSize / 2
            canvas.drawText(value.toString(), textX, textY, textPaint)
        }
    }
}

